package ar.edu.sovietrussia.customcomponents.abm.book;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.wicket.markup.html.form.IChoiceRenderer;

/**
 * Simple property-based ChoiceRenderer. Use the given property names as the source to obtain the respective ID and
 * LABEL strings used to render the Choice to the Hosting component.
 * 
 * Example:
 * 
 * //somewhere, in SomePersistentData.java file... public class SomePersistentData implements Serializable { private
 * Integer id; private String description; //plus, getters and setters.... }
 * 
 * //extract Objects from DB List values = myService.findDataElements();
 * 
 * add( new DropDownChoice( "myWicketId", new PropertyModel(myDataObject, "propertyName" ), values, new
 * PropertyChoiceRenderer( "id", "description" ) ))
 * 
 * @author Davide Alberto Molin (davide.molin@gmail.com)
 */
public class PropertyChoiceRenderer<T> implements IChoiceRenderer<T> {

    private static final long serialVersionUID = 1L;

    // name of the property used to extract the ID for the choice option
    private String idProperty;

    // name of the property used to extract the LABEL for the choice option
    private String valueProperty;

    public PropertyChoiceRenderer(final String idProperty, final String valueProperty) {
        this.idProperty = idProperty;
        this.valueProperty = valueProperty;
    }

    public String getIdProperty() {
        return this.idProperty;
    }

    public void setIdProperty(final String idProperty) {
        this.idProperty = idProperty;
    }

    public String getValueProperty() {
        return this.valueProperty;
    }

    public void setValueProperty(final String valueProperty) {
        this.valueProperty = valueProperty;
    }

    @Override
    public Object getDisplayValue(final T object) {
        return this.getPropertyValue(object, this.valueProperty);
    }

    @Override
    public String getIdValue(final T object, final int index) {
        return this.getPropertyValue(object, this.idProperty).toString();
    }

    private Object getPropertyValue(final T object, final String property) {
        try {
            return BeanUtils.getProperty(object, property);
        } catch (Exception err) {
            // in case of exception, fall back to simple toString...
            return object.toString();
        }
    }
}
